import React, { createContext } from 'react';
import { FormComponentProps } from 'antd/es/form';
import { connect, DispatchProp } from 'dva';

import { StoreState } from '@/common/store/store';
import { Brand } from '@/models/brand';
import { ProductCategory } from '../../../models/productCategory';
import SearchForm from './components/SearchForm';
import ProductListTable, { ProductTableProps } from './components/ProductListTable';
import { Product } from '../../../models/product';

interface ProductListProps extends ProductTableProps, DispatchProp {
  brands: Brand[];
  categories: ProductCategory[];
  loading?: boolean;
}

export const ProductTableContext = createContext<ProductList>({} as ProductList);

export class ProductList extends React.Component<ProductListProps> {
  formRef!: React.Component<FormComponentProps>;

  saveFormRef = (formRef: any) => {
    console.log(formRef);
    this.formRef = formRef;
  };

  handleSearch = () => {
    const { form } = this.formRef.props;
    const { dispatch } = this.props;
    dispatch({
      type: 'product/query',
      payload: form.getFieldsValue(),
    });
  };

  handleReset = () => {
    const { form } = this.formRef.props;
    form.resetFields();
  };

  onRowEdit = (id: number) => {};

  onRowDelete = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'product/remove',
      payload: id,
    });
  };

  onRowUpdate(product: Product) {
    const { dispatch } = this.props;
    dispatch({
      type: 'product/update',
      payload: product,
    });
  }

  render() {
    return (
      <div className="row-group">
        <SearchForm
          brands={this.props.brands}
          categories={this.props.categories}
          wrappedComponentRef={this.saveFormRef}
          onSearch={this.handleSearch}
          onReset={this.handleReset}
        />
        <ProductTableContext.Provider value={this}>
          <ProductListTable products={this.props.products} loading={this.props.loading} />
        </ProductTableContext.Provider>
      </div>
    );
  }
}

const mapStateToProps = (state: StoreState) => ({
  products: state.product.products,
  brands: state.brand.brands,
  categories: state.productCategory.categories,
  loading: state.loading.models.product,
});

export default connect(mapStateToProps)(ProductList);
